package com.train.base.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.SysUserPost;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SnowflakeIdWorker;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysUserService;
import com.train.base.domain.ExamTestPaper;
import com.train.base.domain.PostImproveApplication;
import com.train.base.enums.PostImproveApprovedStateEnums;
import com.train.base.enums.PostImproveTypeEnums;
import com.train.base.mapper.PostImproveApplicationMapper;
import com.train.base.service.IExamTestPaperService;
import com.train.base.service.IPostImproveApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 岗位提升申请Service业务层处理
 *
 * @author keke
 * @date 2024-04-09
 */
@Service
public class PostImproveApplicationServiceImpl implements IPostImproveApplicationService {
    @Autowired
    private PostImproveApplicationMapper postImproveApplicationMapper;
    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private SysUserPostMapper userPostMapper;
    @Autowired
    private ISysPostService iSysPostService;
    @Autowired
    private IExamTestPaperService iExamTestPaperService;

    /**
     * 查询岗位提升申请
     *
     * @param id 岗位提升申请主键
     * @return 岗位提升申请
     */
    @Override
    public PostImproveApplication selectPostImproveApplicationById(Long id) {
        return postImproveApplicationMapper.selectPostImproveApplicationById(id);
    }

    /**
     * 查询岗位提升申请列表
     *
     * @param postImproveApplication 岗位提升申请
     * @return 岗位提升申请
     */
    @Override
    public List<PostImproveApplication> selectPostImproveApplicationList(PostImproveApplication postImproveApplication) {
        List<PostImproveApplication> postImproveApplications = postImproveApplicationMapper.selectPostImproveApplicationList(postImproveApplication);
        Map<Long, String> postMap = new HashMap<>(postImproveApplications.size());
        Map<Long, String> userMap = new HashMap<>(postImproveApplications.size());
        // 查询岗位的名称
        List<Long> postIds = postImproveApplications.stream().map(PostImproveApplication::getPostId).toList();
        if (!ObjectUtils.isEmpty(postIds)) {
            postMap = iSysPostService.selectPostListByIds(postIds).stream().collect(Collectors.toMap(SysPost::getPostId, SysPost::getPostName));
        }
        // 查询用户名称
        List<Long> userIds = postImproveApplications.stream().flatMap(application -> Stream.of(application.getApplicant(), application.getReviewer())).toList();
        if (!ObjectUtils.isEmpty(userIds)) {
            userMap = iSysUserService.selectUserByIds(userIds).stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getUserName));
        }
        for (PostImproveApplication apply : postImproveApplications) {
            if (!ObjectUtils.isEmpty(postMap.get(apply.getPostId()))) {
                apply.setPostName(postMap.get(apply.getPostId()));
            }
            if (!ObjectUtils.isEmpty(userMap.get(apply.getApplicant()))) {
                apply.setApplicantName(userMap.get(apply.getApplicant()));
            }
            if (!ObjectUtils.isEmpty(userMap.get(apply.getReviewer()))) {
                apply.setReviewerName(userMap.get(apply.getReviewer()));
            }
        }
        return postImproveApplications;
    }

    /**
     * 新增岗位提升申请
     *
     * @param postImproveApplication 岗位提升申请
     * @return 结果
     */
    @Override
    public int insertPostImproveApplication(PostImproveApplication postImproveApplication) {
        // 查询登录用户的岗位信息
        Long userId = SecurityUtils.getUserId();
        List<SysUserPost> sysUserPosts = iSysUserService.selectPostWithLevel(userId);
        SysUserPost sysUserPost = sysUserPosts.stream().filter(userPost -> userPost.getPostId().equals(postImproveApplication.getPostId())).findFirst().orElse(null);
        if (PostImproveTypeEnums.LEVEL.getCode().equals(postImproveApplication.getType())) {
            postImproveApplication.setOldCode(sysUserPost != null ? sysUserPost.getPostLevelCode() : null);
        } else {
            postImproveApplication.setOldCode(sysUserPost != null ? sysUserPost.getPostAbility() : null);
        }
        postImproveApplication.setApplicant(userId);
        postImproveApplication.setId(SnowflakeIdWorker.build().nextId());
        postImproveApplication.setPostId(postImproveApplication.getPostId());
        postImproveApplication.setState(PostImproveApprovedStateEnums.WAIT.getCode());
        postImproveApplication.setCreateTime(LocalDateTime.now());
        // 根据用户的id和岗位id，查询最近一次的岗位考试
        ExamTestPaper examTestPaper = iExamTestPaperService.selectExamTestPaperByUserId(userId, postImproveApplication.getPostId());
        if(ObjectUtils.isEmpty(examTestPaper)) {
           throw new RuntimeException("没有查询到关于该岗位的考试记录, 请重新选择!");
        }
        postImproveApplication.setExamPaperId(examTestPaper.getId());
        return postImproveApplicationMapper.insertPostImproveApplication(postImproveApplication);
    }

    /**
     * 修改岗位提升申请
     *
     * @param postImproveApplication 岗位提升申请
     * @return 结果
     */
    @Override
    public int updatePostImproveApplication(PostImproveApplication postImproveApplication) {
        postImproveApplication.setUpdateTime(DateUtils.getNowDate());
        postImproveApplication.setReviewer(SecurityUtils.getUserId());
        if (postImproveApplication.getState().equals(PostImproveApprovedStateEnums.PASS.getCode())) {
            // 修改用户信息
            List<SysUserPost> sysUserPosts = iSysUserService.selectPostWithLevel(postImproveApplication.getApplicant());
            for (SysUserPost sysUserPost : sysUserPosts) {
                if (sysUserPost.getPostId().equals(postImproveApplication.getPostId())) {
                    if (postImproveApplication.getType().equals(PostImproveTypeEnums.LEVEL.getCode())) {
                        if (sysUserPost.getPostLevelCode().equals(postImproveApplication.getOldCode())) {
                            // 提升能力
                            sysUserPost.setPostLevelCode(postImproveApplication.getToCode());
                            userPostMapper.update(sysUserPost);
                        }
                    } else {
                        if (sysUserPost.getPostAbility().equals(postImproveApplication.getOldCode())) {
                            // 提升能力
                            sysUserPost.setPostAbility(postImproveApplication.getToCode());
                            userPostMapper.update(sysUserPost);
                        }
                    }
                }
            }
        }
        return postImproveApplicationMapper.updatePostImproveApplication(postImproveApplication);
    }

    /**
     * 批量删除岗位提升申请
     *
     * @param ids 需要删除的岗位提升申请主键
     * @return 结果
     */
    @Override
    public int deletePostImproveApplicationByIds(Long[] ids) {
        return postImproveApplicationMapper.deletePostImproveApplicationByIds(ids);
    }

    /**
     * 删除岗位提升申请信息
     *
     * @param id 岗位提升申请主键
     * @return 结果
     */
    @Override
    public int deletePostImproveApplicationById(Long id) {
        return postImproveApplicationMapper.deletePostImproveApplicationById(id);
    }
}
